package com.mall.shopping.services;

import com.mall.shopping.IHomeService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.IHomepageConverter;
import com.mall.shopping.dal.entitys.Panel;
import com.mall.shopping.dal.entitys.PanelContentItem;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.HomePageResponse;
import com.mall.shopping.dto.PanelDto;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

/**
 * 创建日期: 2022-01-19-20-21
 * author : XGQ
 * description: 服务提供者实现类
 */
@Service
public class IHomepageServiceImpl implements IHomeService {

    @Autowired
    PanelMapper panelMapper;
    @Autowired
    PanelContentMapper panelContentMapper;

    @Autowired
    IHomepageConverter iHomepageConverter;

    @Override
    public HomePageResponse homepage() {
        // new一个返回值类型的对象，包装
        HomePageResponse response = new HomePageResponse();
        // try..catch 捕获sql是否异常
        try {
            // 获取数据库的信息
            Set<Panel> panels = panelMapper.selectPanelContentAll();
            // 遍历
            for (Panel panel : panels) {
                // 查询数据库
                List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(panel.getId());
                panel.setPanelContentItems(panelContentItems);
            }
            // 对象转化
            Set<PanelDto> panelContentDtos = iHomepageConverter.iHomepageDtos(panels);

            // 执行成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            response.setPanelContentItemDtos(panelContentDtos);
        } catch (Exception e) {
            // 执行失败
            e.printStackTrace();
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }

        return response;
    }
}
